# -*- coding: utf-8 -*-
from Util.Return import *
from Util.Process import *
from Util.SQL import *
from datetime import datetime


class Task:
    def __init__(self, data_list, model_name):
        ############################初始化任务信息
        self.model_name = model_name  # 任务所属的模型
        self.scene_id = data_list[0]  # 数据景号
        self.data_list = data_list  # 当前数据集的ID
        self.tile = "ALL_ALL"  # 数据瓦片范围号
        self.user_id = 0  # 用户ID
        self.state = "init"  # 0为就绪、1为等待、2为运行、3为成功、4为失败
        self.task_id = f"{self.model_name}_{self.tile}_{self.scene_id}"  # 任务ID
        self.json = {"data_list": self.data_list}  # 额外信息

        self.init()  # 创建任务,并调度资源

    def init(self):
        self.status("init")
        json_task = {
            'task_id': self.task_id,
            'model_name': self.model_name,
            'scene_id': self.scene_id,
            'tile': self.tile,
            'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            'state': self.state,
            'user_id': self.user_id,
            'json': self.json
        }
        insert([json_task], 'task')
        self.wait()

    def wait(self):
        self.status("wait")
        self.run()  # 进入运行状态

    def run(self):
        self.status("run")
        self.end("success")

    def end(self, state):
        self.status(state)

    def status(self, state):
        self.state = state
        INFO("INFO", f"TASK {self.task_id} {self.state}")
        update_json = {'state': self.state}
        update(update_json, f'task_id = "{self.task_id}"', 'task')


def Init_Task(data_list, model_name):  # 创建一个新的任务
    task = Task(data_list, model_name)


Init_Task(["S1A_IW_GRDH_1SDV_20230414T100603_20230414T100628_048091_05C7F9_08B3"], "CWSAM")
